package ru.vpitervip.app.client.ui;

import java.util.List;
import java.util.logging.Logger;

import ru.vpitervip.app.client.App;
import ru.vpitervip.app.client.util.MyGeocoderCallback;
import ru.vpitervip.app.client.util.Settings;
import ru.vpitervip.client.managed.request.FacilityProxy;
import ru.vpitervip.client.managed.request.FlatProxy;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.maps.client.MapOptions;
import com.google.gwt.maps.client.MapTypeId;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.base.HasInfoWindowOptions;
import com.google.gwt.maps.client.base.HasLatLng;
import com.google.gwt.maps.client.base.InfoWindow;
import com.google.gwt.maps.client.base.InfoWindowOptions;
import com.google.gwt.maps.client.base.LatLng;
import com.google.gwt.maps.client.event.Event;
import com.google.gwt.maps.client.event.EventCallback;
import com.google.gwt.maps.client.geocoder.Geocoder;
import com.google.gwt.maps.client.geocoder.GeocoderRequest;
import com.google.gwt.maps.client.geocoder.HasGeocoder;
import com.google.gwt.maps.client.geocoder.HasGeocoderRequest;
import com.google.gwt.maps.client.geocoder.HasGeocoderResult;
import com.google.gwt.maps.client.overlay.HasMarker;
import com.google.gwt.maps.client.overlay.Marker;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.CustomScrollPanel;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HorizontalScrollbar;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.NativeHorizontalScrollbar;
import com.google.gwt.user.client.ui.NativeVerticalScrollbar;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Hyperlink;

public class FlatView extends Composite {

	private static final Logger log = Logger.getLogger(FlatsView.class.getName());
	
	
	private static FlatViewUiBinder uiBinder = GWT
			.create(FlatViewUiBinder.class);
	@UiField HorizontalPanel imagePanel;
	@UiField Button bookButton;
	@UiField HTML price;
	@UiField VerticalPanel detailsPanel;
	@UiField HTML descriptionHtml;
	@UiField TabPanel tabPanel;
	@UiField HTML facilitiesHtml;
	@UiField SimplePanel mapPanel;
	@UiField Anchor backToMapButton;
	
//	@UiField(provided=true) CustomScrollPanel photoScrollPanel=new CustomScrollPanel(App.getScrollBarResources());
//	
//	@UiField ScrollPanel descriptionScrollPanel;
//	
	private FlatProxy flatProxy;
	
	private MapWidget mapWidget;
	
	private HasMarker marker;
	
	private Presenter listener;
	
	
	
	public interface Presenter{
		
		void backToMap();

		void showBookingView(int flatId, boolean standAlone);
		
		
	}
	

	interface FlatViewUiBinder extends UiBinder<Widget, FlatView> {
	}

	public FlatView() {
		initWidget(uiBinder.createAndBindUi(this));
		init();
		
	}

	public FlatView(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));
		init();
		
	}
	
	public void setPresenter(Presenter listener){
		this.listener=listener;
		
	}
    
	
	private void init(){
		
//		tabPanel.addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() {
//			
//			@Override
//			public void onBeforeSelection(BeforeSelectionEvent<Integer> event) {
//				if (event.getItem()==2){
//					mapPanel.setWidget(getMapWidget());
//				}
//				
//			}
//		});
		
		addStyleName(App.getAppResources().style().elementStyle());
		
		tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
			
			@Override
			public void onSelection(SelectionEvent<Integer> event) {
				if (event.getSelectedItem()==2){
					mapPanel.setWidget(getMapWidget());
					updateMap();
				}
				
			}
		});
		
		
		backToMapButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
			    if (listener!=null) listener.backToMap();
			}
			
		});
		
		
		bookButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				listener.showBookingView(flatProxy.getId().intValue(),false);
				
			}
			
		});
		
//		NativeHorizontalScrollbar horizontalScrollbar=new NativeHorizontalScrollbar(App.getHorizontalScrollBarResources());
//		photoScrollPanel.setHorizontalScrollbar(horizontalScrollbar, 20);
		
		
//		NativeVerticalScrollbar verticalScrollbar=new NativeVerticalScrollbar(App.getVerticalScrollBarResources());
//		descriptionScrollPanel.setVerticalScrollbar(verticalScrollbar, 20);
//		descriptionScrollPanel.setWidth("100%");
		
		
	}
	
	
	public void setFlat(FlatProxy flatProxy, boolean standAlone){
		
		if (flatProxy==null) return;
		
		log.info("setFlat  flatId:"+flatProxy.getId()+"  standAlone:"+standAlone);
		
		imagePanel.clear();
		this.flatProxy=flatProxy;
		
		if (flatProxy.getFotos()!=null&&flatProxy.getFotos().size()>0){
			
			final PopupPanel imagePopup = new PopupPanel(true);
			
			for (int i=0;i<flatProxy.getFotos().size();i++){
				final String path=flatProxy.getFotos().get(i).getPath().substring(8);
				Image image=new Image("http://sutki-piter.ru/fotos/"+path);
				image.setHeight("100px");
//				image.setWidth(Math.min(image.getWidth(), 110)+"px");
				image.addStyleName(App.getAppResources().style().thumbImage());
				imagePanel.add(image);		
				
				image.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						
						final Image imageFull = new Image("http://sutki-piter.ru/showvipimage.php?foto=bigfoto/"+path);
			
						AbsolutePanel absolutePanel=new AbsolutePanel();
						absolutePanel.add(imageFull);
//						absolutePanel.add(new Label("vpiter-vip.ru"),150,150);
//						absolutePanel.setSize(imageFull.getWidth()+"px", imageFull.getHeight()+"px");
						
						imageFull.addLoadHandler(new LoadHandler() {
							
							@Override
							public void onLoad(LoadEvent event) {
								imagePopup.setSize(imageFull.getWidth()+"px", imageFull.getHeight()+"px");
								imagePopup.center();
							}
						});
						
					    imagePopup.setAnimationEnabled(true);
					    imagePopup.ensureDebugId("cwBasicPopup-imagePopup");
					    imagePopup.setWidget(absolutePanel);
					    imageFull.addClickHandler(new ClickHandler() {
					      public void onClick(ClickEvent event) {
					        imagePopup.hide();
					      }
					    });
					    imagePopup.center();
						
					}
				});
				
			}
			
			
		}
		
		
		detailsPanel.clear();
		detailsPanel.add(new HTML("<font size='2'>"+"<b>Id:</b>"+flatProxy.getId()));
		if (flatProxy.getMetroStation()!=null ) detailsPanel.add(new HTML("<font size='2'>"+"<b>Cтанция метро: </b>"+flatProxy.getMetroStation().getRusName()+"</font>"));
		if (flatProxy.getSleepPlaceNum()!=null&&flatProxy.getSleepPlaceNum().length()>0 ) detailsPanel.add(new HTML("<font size='2'>"+"<b>Спальные места: </b>"+flatProxy.getSleepPlaceNum()+"</font>"));
		if (flatProxy.getFloor()!=null ) detailsPanel.add(new HTML("<font size='2'>"+"<b>Этаж: </b>"+flatProxy.getFloor()+"</font>"));
		if (flatProxy.getArea()!=null ) detailsPanel.add(new HTML("<font size='2'>"+"<b>Общая площадь: </b>"+flatProxy.getArea()+" м²"+"</font>"));
		if (flatProxy.getRoomNum()!=null ) detailsPanel.add(new HTML("<font size='2'>"+"<b>Кол-во комнат: </b>"+flatProxy.getRoomNum()+"</font>"));
		
		
		
		price.setHTML("<div class='important'>"+flatProxy.getPrice()+" руб./сут."+"</div>");
		
		
		
		
		
		
		
		String facilitiesInnerHtml="<table><tr valign='top'>";
		
		if (flatProxy.getFacilities()!=null&&flatProxy.getFacilities().size()>0){
			
			int facilitiesInCol=(flatProxy.getFacilities().size()+1)/2;
			
			List<FacilityProxy> facilityProxies=flatProxy.getFacilities();
			int proxiesSize=facilityProxies.size();
			FacilityProxy minProxy;
			for (int i=0;i<proxiesSize;i++){
				minProxy=facilityProxies.get(0);
				for (FacilityProxy facilityProxy:facilityProxies){
					int facNum=facilityProxy.getNum();
					int minNum=minProxy.getNum();
					if (facNum<minNum) minProxy=facilityProxy;
				}
				facilityProxies.remove(minProxy);
				
				if (i%facilitiesInCol==0) {
					if(i!=0) facilitiesInnerHtml+="</ul></td>";
					facilitiesInnerHtml+="<td align='left'><ul style='list-style: none;text-align:left;padding-left: 1px'>";
				}
				
//				if (i>0&&i<proxiesSize) facilitiesInnerHtml+=", ";
				facilitiesInnerHtml+="<li><image src='images/check.png' style='padding-left:15px;padding-right:4px;padding-top:2px' />"+minProxy.getDescription()+"</li>";
//				if (i==proxiesSize-1) facilitiesInnerHtml+=".";
				
				if (i==proxiesSize-1) facilitiesInnerHtml+="</tr></table>";
			
			}
			
			
		}
		facilitiesInnerHtml+="</tr></table>";
		
		descriptionHtml.setHTML("<font size='2'>"+flatProxy.getDescription()+"</font>");
		facilitiesHtml.setHTML(facilitiesInnerHtml);
	
	    tabPanel.selectTab(0);
	    
    	backToMapButton.setVisible(!standAlone);
    	bookButton.setVisible(!standAlone);
	    
	    if (standAlone){
	    
	    	listener.showBookingView(flatProxy.getId().intValue(),true);
	    	
	    }

	
	}

private MapWidget getMapWidget(){
		
		if (mapWidget==null){
			
	
				final MapOptions options = new MapOptions();
			    // Zoom level. Required
			    options.setZoom(13);
			   
			    options.setCenter(new LatLng(59.946104,30.295516));
			    // Map type. Required.
			    options.setMapTypeId(new MapTypeId().getRoadmap());
			    
			    // Enable maps drag feature. Disabled by default.
			    options.setDraggable(true);
			    // Enable and add default navigation control. Disabled by default.
			    options.setNavigationControl(true);
			    // Enable and add map type control. Disabled by default.
			    options.setMapTypeControl(true);
			    mapWidget = new MapWidget(options);
			    mapWidget.setSize("448px", "302px");
			    
                
			
		}
		
		return mapWidget;
	}

   private void updateMap(){
	   if (flatProxy==null) return; 
	  setMarker(flatProxy); 
   }
   
   
   private void  setMarker(final FlatProxy flatProxy){  
		
   	double lat=flatProxy.getLat();
		double lon=flatProxy.getLon();
		
		final String address=flatProxy.getAddress();
		
		if (lat>0&&lon>0){

			HasLatLng latLng=new LatLng(lat, lon);

			setMarker(latLng,flatProxy);


		}else{
			
			if (Settings.IS_DEBUGGING==1) return;
			
			if (address==null||address.length()<4) return;
			
			final HasGeocoderRequest gRequest =  new GeocoderRequest();
	        gRequest.setAddress("Санкт-Петербург "+address);
	        final HasGeocoder geocoder = new Geocoder();
	        geocoder.geocode(gRequest, new MyGeocoderCallback() {
	          
	          @Override
	          public void callback(List<HasGeocoderResult> responses, String status) {
//	        	  System.out.println("Answer received");
	            if (status.equals("OK")&&responses!=null&&responses.size()>0) {
	            	
	              final HasGeocoderResult gResult = responses.get(0);
	              final HasLatLng latLng = gResult.getGeometry().getLocation();
	              
	              setMarker(latLng,flatProxy);
	              
	            } else {
	              Window.alert("Geocoder failed with response : " + status);
	            }
	          }

			
	        });
		}
		
		
	}
   
   private void  setMarker(HasLatLng gLatLng,final FlatProxy flatProxy) {
	
       if (marker==null){
      	 marker = new Marker();
      	 marker.setMap(mapWidget.getMap());
       }
       marker.setPosition(gLatLng);
      
     
       mapWidget.getMap().panTo(gLatLng);
		
	}

}
